Skip to main content

Sending and Landing Transactions

In this guide, we'll explore how to send transactions to the Solana blockchain for any Solana project. We'll cover two approaches:

  1. Using the simplified tx-sender library - a lightweight solution that works with any Solana project
  2. The manual approach using Solana's native SDKs directly

The Easy Way: Using tx-sender

The tx-sender library is a lightweight package designed to simplify transaction building and sending in Solana. It handles all the complex aspects like priority fees, Jito tips, compute unit estimation, and retry logic automatically.

Installation

package.json
"dependencies": {
"@orca-so/tx-sender": "^1.0.0"
},

Usage

sendTransaction.ts
import {
setRpc,
setPriorityFeeSetting,
setJitoTipSetting,
buildAndSendTransaction
} from "@orca-so/tx-sender";
import { createSignerFromKeypair } from "@solana/kit";

// Initialize RPC connection (required)
await setRpc("https://api.mainnet-beta.solana.com");

// Get instructions from Whirlpools SDK
const { instructions } = // your whirlpool instructions here

// Build and send transaction with default fee settings
const signature = await buildAndSendTransaction(
instructions,
wallet // your wallet signer
);

console.log(`Transaction confirmed: ${signature}`);

Configuration Options

The tx-sender library provides flexible configuration options to optimize your transaction sending strategy. Let's break these down in detail:

Default Settings

By default, tx-sender uses the following configuration:

  • Priority Fees: Dynamic pricing with a max cap of 0.004 SOL (4,000,000 lamports)
  • Jito Tips: Dynamic pricing with a max cap of 0.004 SOL (4,000,000 lamports)
  • Compute Unit Margin: 1.1x multiplier for compute unit calculation (10% margin)
  • Jito Block Engine URL: https://bundles.jito.wtf

Priority Fee Configuration

Priority fees incentivize validators to include your transaction in blocks. The tx-sender library supports three priority fee strategies:

Understanding Dynamic Fees and Percentiles

When using the "dynamic" fee strategy, tx-sender automatically analyzes recent network conditions to determine an appropriate fee. The system works by:

  1. Calling the getRecentPrioritizationFees RPC method, which returns data about fees from the last 150 blocks
  2. Sorting these fees from lowest to highest
  3. Selecting a specific percentile from this data

The tx-sender library allows capping these dynamic fees at a maximum amount to prevent excessive spending during extreme network conditions.

Note: The tx-sender library automatically filters out zero-fee transactions before calculating percentiles. This ensures that during periods of low network activity when many blocks have zero fees, your transaction still has an appropriate non-zero fee to improve landing probability.

// 1. Dynamic fees - automatically adjusts based on network conditions
setPriorityFeeSetting({
type: "dynamic",
maxCapLamports: BigInt(5_000_000), // Optional: Cap at 0.005 SOL (default: 4,000,000)
});

// 2. Exact fees - specify an exact amount
setPriorityFeeSetting({
type: "exact",
amountLamports: BigInt(10_000), // Exactly 0.00001 SOL
});

// 3. No priority fees
setPriorityFeeSetting({
type: "none",
});

// Set a specific priority fee percentile (applicable for dynamic fees)
// Available values: "25", "50", "75", "95", "99"
setPriorityFeePercentile("75"); // Use 75th percentile (default: "50")

Jito Tip Configuration

Jito tips are additional fees that go to Jito MEV (Maximal Extractable Value) validators, who represent approximately 85% of Solana's validator stake. These tips can improve transaction landing probability even further than regular priority fees.

Understanding Jito Tips and Dynamic Pricing

Jito tips work similarly to priority fees but are specifically for Jito validators. When using dynamic Jito tips:

  1. The percentile system works the same way as with priority fees - selecting from recent fee data
  2. Jito offers an additional option: "50ema" (Exponential Moving Average), which smooths out fee spikes by using a weighted average
  3. Jito tips are sent directly to the Jito block engine rather than through the regular fee mechanism

Using Jito tips is particularly effective because:

  • Jito validators account for about 85% of Solana's stake weight
  • They use a specialized searching algorithm to look for higher-tipped transactions
  • During congestion, Jito validators can help your transaction land faster

Like priority fees, Jito tips can be capped to prevent excessive spending. The default cap is 4,000,000 lamports (0.004 SOL).

// 1. Dynamic Jito tips
setJitoTipSetting({
type: "dynamic",
maxCapLamports: BigInt(3_000_000), // Optional: Cap at 0.003 SOL (default: 4,000,000)
});

// 2. Exact Jito tip
setJitoTipSetting({
type: "exact",
amountLamports: BigInt(20_000), // Exactly 0.00002 SOL
});

// 3. No Jito tips
setJitoTipSetting({
type: "none",
});

// Set a specific Jito fee percentile or use EMA
// Available values: "25", "50", "75", "95", "99", "50ema"
setJitoFeePercentile("50ema"); // Use 50th percentile exponential moving average

// Set custom Jito block engine URL (defaults to "https://bundles.jito.wtf")
setJitoBlockEngineUrl("https://your-jito-service.com");

Compute Unit Configuration

The compute units represent the computational resources your transaction requires. The margin multiplier adds extra units as a safety buffer to prevent transaction failures.

How Compute Unit Estimation Works

When sending a transaction, tx-sender performs these steps to optimize compute unit usage:

  1. First, it simulates your transaction on the RPC to estimate the required compute units
  2. Then, it applies the margin multiplier to add a safety buffer (default is 1.1, or 10% extra)
  3. Finally, it sets a compute unit limit instruction at the beginning of your transaction

This process ensures that your transaction:

  • Has enough compute units to complete execution
  • Doesn't allocate unnecessarily high compute units (which would cost more in fees)
  • Has a safety margin to account for differences between simulation and actual execution

Setting an appropriate margin is important because:

  • Too low (close to 1.0): Transaction might fail with "out of compute units" error if network conditions change
  • Too high (over 1.5): Transactions that request higher compute units get lower priority for the same prioritization fee. Higher compute units signal to validators that your transaction will use more resources.

For most transactions, a value between 1.1 and 1.2 (10-20% margin) is appropriate. For complex or unpredictable transactions, you might want to use a higher value like 1.3 or 1.4.

import {
setRpc,
setPriorityFeeSetting,
setPriorityFeePercentile,
setJitoTipSetting,
setJitoFeePercentile,
setComputeUnitMarginMultiplier,
setJitoBlockEngineUrl,
buildAndSendTransaction
} from "@orca-so/tx-sender";

// 1. Set up RPC connection
await setRpc("https://api.mainnet-beta.solana.com");

// 2. Configure priority fees
setPriorityFeeSetting({
type: "dynamic",
maxCapLamports: BigInt(5_000_000), // 0.005 SOL
});
setPriorityFeePercentile("75");

// 3. Configure Jito tips
setJitoTipSetting({
type: "dynamic",
maxCapLamports: BigInt(3_000_000), // 0.003 SOL
});
setJitoFeePercentile("50ema");

// 4. Set compute unit margin
setComputeUnitMarginMultiplier(1.2);

// 5. Optional: Custom Jito endpoint
setJitoBlockEngineUrl("https://bundles.jito.wtf");

// 6. Send transaction with configured settings
const signature = await buildAndSendTransaction(
instructions,
wallet
);

The Manual Way: Using Solana SDKs Directly

In this section, we'll explore how to send the instructions using the Solana SDK directly - both in Typescript and Rust. We'll cover the following key topics:

  • Client-side retry
  • Prioritization fees
  • Compute budget estimation

We also cover key considerations for sending transactions in web applications with wallet extensions, along with additional steps to improve transaction landing.

Code Overview

1. Dependencies

Let's start by importing the necessary dependencies from Solana's SDKs.

package.json
"dependencies": {
"@solana-program/compute-budget": "^0.6.1",
"@solana/kit": "^2.1.0",
},
sendTransaction.ts
import {
createSolanaRpc,
address,
pipe,
createTransactionMessage,
setTransactionMessageFeePayer,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstructions,
prependTransactionMessageInstructions,
signTransactionMessageWithSigners,
getComputeUnitEstimateForTransactionMessageFactory,
getBase64EncodedWireTransaction,
setTransactionMessageFeePayerSigner
} from '@solana/kit';
import {
getSetComputeUnitLimitInstruction,
getSetComputeUnitPriceInstruction
} from '@solana-program/compute-budget';

2. Create Transaction Message From Instructions

To send a transaction on Solana, you need to include a blockhash to the transaction. A blockhash acts as a timestamp and ensures the transaction has a limited lifetime. Validators use the blockhash to verify the recency of a transaction before including it in a block. A transaction referencing a blockhash is only valid for 150 blocks (~1-2 minutes, depending on slot time). After that, the blockhash expires, and the transaction will be rejected.

Durable Nonces: In some cases, you might need a transaction to remain valid for longer than the typical blockhash lifespan, such as when scheduling future payments or collecting multi-signature approvals over time. In that case, you can use durable nonces to sign the transaction, which includes a nonce in place of a recent blockhash.

You also need to add the signers to the transactions. With Solana Kit, you can create instructions and add additional signers as TransactionSigner to the instructions. The Typescript Whirlpools SDK leverages this functioanlity and appends all additional signers to the instructions for you. In Rust, this feautures is not available. Therefore, the Rust Whirlpools SDK may return instruction_result.additional_signers if there are any, and you need to manually append them to the transaction.

Here's how the transaction message is created:

sendTransaction.ts
const { instructions } = // get instructions from Whirlpools SDK
const latestBlockHash = await rpc.getLatestBlockhash().send();
const transactionMessage = await pipe(
createTransactionMessage({ version: 0}),
tx => setTransactionMessageFeePayer(wallet.address, tx),
tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockHash.value, tx),
tx => appendTransactionMessageInstructions(instructions, tx)
)

3. Estimating Compute Unit Limit and Prioritization Fee

Before sending a transaction, it's important to set a compute unit limit and an appropriate prioritization fee.

Transactions that request fewer compute units get high priority for the same amount of prioritization fee (which is defined per compute unit). Setting the compute units too low will result in a failed transaction.

You can get an estimate of the compute units by simulating the transaction on the RPC. To avoid transaction failures caused by underestimating this limit, you can add an additional 100,000 compute units, but you can adjust this based on your own tests.

The prioritization fee per compute unit also incentivizes validators to prioritize your transaction, especially during times of network congestion. You can call the getRecentPrioritizationFees RPC method to retrieve an array of 150 values, where each value represents the lowest priority fee paid for transactions that landed in each of the past 150 blocks. In this example, we sort that list and select the 50th percentile, but you can adjust this if needed. The prioritization fee is provided in micro-lamports per compute unit. The total priority fee in lamports you will pay is calculated as (estimated compute unitsprioritization fee)/106(\text{estimated compute units} \cdot \text{prioritization fee}) / 10^6.

sendTransaction.ts
const getComputeUnitEstimateForTransactionMessage =
getComputeUnitEstimateForTransactionMessageFactory({
rpc
});
const computeUnitEstimate = await getComputeUnitEstimateForTransactionMessage(transactionMessage) + 100_000;
const medianPrioritizationFee = await rpc.getRecentPrioritizationFees()
.send()
.then(fees =>
fees
.map(fee => Number(fee.prioritizationFee))
.sort((a, b) => a - b)
[Math.floor(fees.length / 2)]
);
const transactionMessageWithComputeUnitInstructions = await prependTransactionMessageInstructions([
getSetComputeUnitLimitInstruction({ units: computeUnitEstimate }),
getSetComputeUnitPriceInstruction({ microLamports: medianPrioritizationFee })
], transactionMessage);

4. Sign and Submit Transaction

Finally, the transaction needs to be signed, encoded, and submitted to the network. A client-side time-base retry mechanism ensures that the transaction is repeatedly sent until it is confirmed or the time runs out. We use a time-based loop, because we know that the lifetime of a transaction is 150 blocks, which on average takes about 79-80 seconds. The signing of the transactions is an idempotent operation and produces a transaction hash, which acts as the transaction ID. Since transactions can be added only once to the block chain, we can keep sending the transaction during the lifetime of the trnsaction.

You're probably wondering why we don't just use the widely used sendAndConfirm method. This is because the retry mechanism of the sendAndConfirm method is executed on the RPC. By default, RPC nodes will try to forward (rebroadcast) transactions to leaders every two seconds until either the transaction is finalized, or the transaction's blockhash expires. If the outstanding rebroadcast queue size is greater than 10,000 transaction, newly submitted transactions are dropped. This means that at times of congestion, your transaction might not even arrive at the RPC in the first place. Moreover, the confirmTransaction RPC method that sendAndConfirm calls is deprecated.

sendTransaction.ts
const signedTransaction = await signTransactionMessageWithSigners(transactionMessageWithComputeUnitInstructions)
const base64EncodedWireTransaction = getBase64EncodedWireTransaction(signedTransaction);

const timeoutMs = 90000;
const startTime = Date.now();

while (Date.now() - startTime < timeoutMs) {
const transactionStartTime = Date.now();

const signature = await rpc.sendTransaction(base64EncodedWireTransaction, {
maxRetries: 0n,
skipPreflight: true,
encoding: 'base64'
}).send();

const statuses = await rpc.getSignatureStatuses([signature]).send();
if (statuses.value[0]) {
if (!statuses.value[0].err) {
console.log(`Transaction confirmed: ${signature}`);
break;
} else {
console.error(`Transaction failed: ${statuses.value[0].err.toString()}`);
break;
}
}

const elapsedTime = Date.now() - transactionStartTime;
const remainingTime = Math.max(0, 1000 - elapsedTime);
if (remainingTime > 0) {
await new Promise(resolve => setTimeout(resolve, remainingTime));
}
}

Handling transactions with Wallets in web apps.

Creating Noop Signers

When sending transactions from your web application, users need to sign the transaction using their wallet. Since the transaction needs to assembled beforehand, you can create a noopSigner (no-operation signer) and add it to the instructions. This will act as a placeholder for you instructions, indicating that a given account is a signer and the signature wil be added later. After assembling the transaction you can pass it to the wallet extension. If the user signs, it will return a serialized transaction with the added signature.

Prioritization Fees

Some wallets will calculate and apply priority fees for your transactions, provided:

  • The transaction does not already have signatures present.
  • The transaction does not have existing compute-budget instructions.
  • The transactions will still be less than the maximum transaction size fo 1232 bytes, after applying compute-budget instructions.

Additional Improvements for Landing Transactions

  • You could send your transaction to multiple RPC nodes at the same time, all within each iteration of the time-based loop.
  • At the time of writing, 85% of Solana validators are Jito validators. Jito validators happily accept an additional tip, in the form a SOL transfer, to prioritize a transaction. A good place to get familiarized with Jito is here: https://www.jito.network/blog/jito-solana-is-now-open-source/
  • Solana gives staked validators more reliable performance when sending transactions by routing them through prioritized connections. This mechanism is referred to as stake-weighted Quality of Service (swQoS). Validators can extend this service to RPC nodes, essentially giving staked connections to RPC nodes as if they were validators with that much stake in the network. RPC providers, like Helius and Titan, expose such peered RPC nodes to paid users, allowing users to send transactions to RPC nodes which use the validator's staked connections. From the RPC, the transaction is then sent over the staked connection with a lower likelihood of being delayed or dropped.